layui.define(
  ["laydate", "table", "laypage", "form", "element"],
  function (exports) {
    var $ = layui.$,
      table = layui.table,
      element = layui.element,
      proID = jTools.getQuery("proID"),
      cate = jTools.getQuery("cate"),
      num = jTools.getQuery("num"),
      element = layui.element,
      projectName = jTools.getQuery("projectName"),
      projectNameNext = jTools.getQuery("projectNameNext"),
      projectNameNextt = jTools.getQuery("projectNameNextt");
    meetingTabId = "";

    $(".layui-breadcrumb").html(
      '<a href="projectManagement.html">' +
        projectName +
        '</a><a href="javascript:history.go(-1)">' +
        projectNameNext +
        '</a><a href="javascript:history.go(-1)">' +
        projectNameNextt +
        "</a>"
    );
    element.init();
    $.ajax({
      async: false,
      url: base_url + "/projectManage/queryProDetailsByProID",
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      method: "post",
      contentType: "application/json",
      data: JSON.stringify({ proID, cate, num }),
      dataType: "json",
      success: function (data) {
        var engineeringSummaryData = data.data.project;
        var technicalAccessoryList = data.data.technicalAccessoryList;
        var flowListData = data.data.flowList;
        $(".no").html(engineeringSummaryData.no);
        $(".projectName").html(engineeringSummaryData.projectName);
        $(".name").html(engineeringSummaryData.name);
        $(".type").html(engineeringSummaryData.type);
        $(".createUser").html(engineeringSummaryData.createUser);
        $(".personName").html(engineeringSummaryData.personName);
        $(".phone").html(engineeringSummaryData.phone);
        $(".email").html(engineeringSummaryData.email);
        $(".buildUnitName").html(engineeringSummaryData.buildUnitName);
        $(".contactName").html(engineeringSummaryData.contactName);
        $(".contactPhone").html(engineeringSummaryData.contactPhone);
        $(".planStartTime").html(engineeringSummaryData.planStartTime);
        $(".responPerson").html(engineeringSummaryData.responPerson);
        $(".responPhone").html(engineeringSummaryData.responPhone);
        $(".metroRelation").html(engineeringSummaryData.metroRelation);
        $(".projectAddr").html(engineeringSummaryData.projectAddr);
        $(".status").html(engineeringSummaryData.status);
        $(".contentt").html(engineeringSummaryData.content);
        $(".managerNumber").html(engineeringSummaryData.managerNumber);
        $(".projectName").html(engineeringSummaryData.projectName);
        $(".lineType").html(engineeringSummaryData.lineType);
        $(".stationFlag").html(engineeringSummaryData.stationFlag);
        $(".stationArea").html(engineeringSummaryData.stationArea);
        if (data.data.cate == 2) {
          projectDocumentTable(data.data.technicalAdviceListZX);
        } else if (data.data.cate == 3) {
          projectDocumentTable(data.data.technicalAdviceListXK);
        } else if (data.data.cate == 4) {
          projectDocumentTable(data.data.specialProtection);
        }
        var flowListTemplate = "";
        for (var i = 0; i < flowListData.length; i++) {
          if (i == flowListData.length - 1) {
            flowListTemplate +=
              "<li class='" +
              (flowListData[i].flag == "1"
                ? "step-active step-end"
                : "step-end") +
              "'><div class='step-line'></div><div class='step-content'><span class='step-num'>" +
              statusIcon(flowListData[i].flow) +
              "</span><div>" +
              flowListData[i].flow +
              "</div><div class='stepTime'>" +
              (flowListData[i].create_time == undefined
                ? ""
                : flowListData[i].create_time) +
              "</div></div></li>";
          } else {
            flowListTemplate +=
              "<li class='" +
              (flowListData[i].flag == "1" ? "step-active" : "") +
              "'><div class='step-line'></div><div class='step-content'><span class='step-num'>" +
              statusIcon(flowListData[i].flow) +
              "</span><div>" +
              flowListData[i].flow +
              "</div><div class='stepTime'>" +
              (flowListData[i].create_time == undefined
                ? " "
                : flowListData[i].create_time) +
              "</div></div></li>";
          }
        }
        $(".flowListStep .steps").html(flowListTemplate);
        function statusIcon(paresm) {
          if (paresm == "待处理") {
            return '<i class="iconfont icon-daichuli"></i>';
          } else if (paresm == "资料校对中") {
            return '<i class="iconfont icon-informatiom"></i>';
          } else if (paresm == "处理中") {
            return '<i class="iconfont icon-ic_wait"></i>';
          } else if (paresm == "已发送") {
            return '<i class="iconfont icon-fasongyoujian"></i>';
          } else if (paresm == "技审草稿被退回待处理") {
            return '<i class="iconfont icon-yifasongyoujian"></i>';
          } else if (paresm == "已完结") {
            return '<i class="iconfont icon-yifasongyoujian"></i>';
          } else if (paresm == "专项草稿审核") {
            return '<i class="iconfont icon-yifasongyoujian"></i>';
          } else if (paresm == "资料校对") {
            return '<i class="iconfont icon-yifasongyoujian"></i>';
          }
        }
        function projectDocumentTable(projectData) {
          table.render({
            elem: "#projectDocumentTable",
            data: projectData || [],
            skin: "nob", // 无边框风格
            cols: [
              [
                {
                  field: "pdfName",
                  title: "文档名称",
                  align: "center",
                  width: 500,
                  templet: function (item) {
                    return (
                      "<div title=" +
                      item.pdfName +
                      " class='whiteSpace'>" +
                      item.pdfName +
                      "</div>"
                    );
                  },
                },
                {
                  field: "createTime",
                  title: "上传时间",
                  align: "center",
                  width: 330,
                },
                {
                  field: "flag",
                  title: "性质",
                  align: "center",
                  templet: "#fileFlag",
                },
                {
                  field: "source",
                  title: "文档来源系统",
                  align: "center",
                  width: 330,
                },
                {
                  title: "操作",
                  align: "center",
                  fixed: "right",
                  width: 200,
                  toolbar: "#projectManagementDetailOprea",
                },
              ],
            ],
          });
        }
        table.on("tool(projectDocumentTable)", function (obj) {
          var data = obj.data;
          if (obj.event === "projectDocumentDown") {
            window.location.href = data.pdfUrl;
          } else if (obj.event === "projectDocumentSee") {
            layer.open({
              title: '<i class="fa fa-plus"></i>&nbsp;文档查看',
              type: 1,
              fix: false,
              skin: "layui-layer-rim",
              area: ["70%", "90%"],
              content: $("#iframePDF").html(),
              success: function () {
                var Iframe =
                  '<iframe id="Iframe" width="100%" height="800px"></iframe>';
                $(".iframePDF").html(Iframe);
                $("#Iframe").attr(
                  "src",
                  "../../layuiadmin/web/viewer.html?file=" + data.pdfUrl
                );
              },
            });
          }
        });

        table.render({
          elem: "#projectDataTable",
          data: engineeringSummaryData.files || [],
          skin: "nob",
          cols: [
            [
              {
                field: "filetype",
                title: "项目类型",
                align: "center",
              },
              {
                field: "fileName",
                title: "项目名称",
                align: "center",
              },
              {
                title: "操作",
                align: "center",
                fixed: "right",
                width: 220,
                toolbar: "#projectDataDetailOprea",
              },
            ],
          ],
        });
        table.on("tool(projectDataTable)", function (obj) {
          var data = obj.data;
          if (obj.event === "projectDataDown") {
            window.location.href = data.url;
          } else if (obj.event === "projectDataSee") {
            layer.open({
              title: '<i class="fa fa-plus"></i>&nbsp;文档查看',
              type: 1,
              fix: false,
              skin: "layui-layer-rim",
              area: ["70%", "90%"],
              content: $("#iframePDF").html(),
              success: function () {
                var Iframe =
                  '<iframe id="Iframe" width="100%" height="800px"></iframe>';
                $(".iframePDF").html(Iframe);
                $("#Iframe").attr(
                  "src",
                  "../../layuiadmin/web/viewer.html?file=" + data.url
                );
              },
            });
          } else if (obj.event === "projectDataDownOther") {
            $.ajax({
              type: "post",
              async: true, //异步执行
              url: "http://10.1.49.89:10003/api/FileUpload/DownFileByFileIDAsync",
              headers: {
                Authorization: layui.sessionData("userToken").key,
                account: layui.sessionData("userName").key,
              },
              contentType: "application/json",
              data: JSON.stringify({ FILE_ID: data.fileEmcId }),
              success: function (data) {
                if ((data.RESULT = true)) {
                  debugger;
                  window.location.href = data.RESPONSE;
                }
              },
            });
          }
        });
        if (technicalAccessoryList.length == 0) {
          $(".enclosureListt").html(" ");
        } else {
          var strr = "";
          technicalAccessoryList.forEach((item) => {
            if (item.extName === "pdf" || item.extName === "PDF") {
              strr += ` <div class="layui-col-md6"><img src='../../layuiadmin/images/pdf.png'/>${item.aessName}<div class="opraBtn" data-id="${item.aessFullnam}"><button class="deleteAttachment layui-btn layui-btn-xs technicalReviewBtn layui-btn-danger" data-id="${item.aessId}">删除</button><button class="layui-btn layui-btn-xs technicalReviewBtn technicalRequirement downPdf">下载</button>
          <button class="seePdf">查看</button></div></div>`;
            } else if (item.extName === "docx") {
              strr += ` <div class="layui-col-md6"><img src='../../layuiadmin/images/word.png'/>${item.aessName}<div class="opraBtn" data-id="${item.aessFullnam}"><button class="deleteAttachment layui-btn layui-btn-xs technicalReviewBtn layui-btn-danger" data-id="${item.aessId}">删除</button><button class="layui-btn layui-btn-xs technicalReviewBtn technicalRequirement downWord">下载</button>
         </div></div>`;
            } else {
              strr += ` <div class="layui-col-md6">${item.aessName}<div class="opraBtn" data-id="${item.aessFullnam}"><button class="deleteAttachment layui-btn layui-btn-xs technicalReviewBtn layui-btn-danger" data-id="${item.aessId}">删除</button><button class="layui-btn layui-btn-xs technicalReviewBtn technicalRequirement downWord">下载</button>
         </div></div>`;
            }
            $(".enclosureListt").html(strr);
          });
        }
      },
    });
    // 下载附件;
    $(".enclosureListt").on("click", ".downWord", function () {
      enclosureAessName = $(this).parent().attr("data-id");
      window.location.href = enclosureAessName;
    });
    //删除附件
    $(".enclosureListt").on("click", ".deleteAttachment", function () {
      var aessid = $(this).attr("data-id");
      var removeElement = $(this).parent().parent();
      $.ajax({
        type: "post",
        async: true, //异步执行
        url: base_url + "/report/deleteProjectotherattachFileByUuid",
        headers: {
          Accept: "application/json; charset=utf-8",
          Authorization: layui.sessionData("userToken").key,
        },
        contentType: "application/json",
        data: JSON.stringify({ aessId: aessid }),
        success: function (data) {
          if ((data.type = "success")) {
            layer.confirm("确认删除吗?", function (index) {
              removeElement.remove();
              layer.close(index);
              layer.msg(data.message, { icon: 6 });
            });
          } else {
            layer.msg(data.message, { icon: 5 });
          }
        },
      });
    });
    $.ajax({
      async: false,
      url: base_url + "/meeting/ids/" + proID,
      headers: {
        Accept: "application/json; charset=utf-8",
        Authorization: layui.sessionData("userToken").key,
      },
      method: "get",
      success: function (data) {
        if (data.code == "200") {
          var conferenceMaterialsData = data.data;
          if (conferenceMaterialsData.length > 0) {
            meetingTabId = conferenceMaterialsData[0].id;
            conferenceMaterialsData.forEach((item, index) => {
              var htmlVido = `<div><table class="meetingProjectDocTable${index}" lay-filter="meetingProjectDocTable${index}"></table></div><div class="meetingVoicesTabList"><div class="layui-tab meetingMinutesTable" lay-filter="meetingVoicesTab${index}" >
              <ul class="layui-tab-title"></ul>
              <div class="layui-tab-content"></div>
          </div></div>`;
              element.tabAdd("conferenceMaterialsTable", {
                title: item.meetingHeadline,
                content: htmlVido,
                id: item.id,
              });
            });
            element.on("tab(conferenceMaterialsTable)", function (data) {
              id = $(this).attr("lay-id");
              $(".meetingMinutesTable .layui-tab-title").html("");
              $(".meetingMinutesTable .layui-tab-content").html("");
              conferenceMaterialsListFun(id, data.index);
            });
            element.tabChange("conferenceMaterialsTable", meetingTabId);
          } else {
          }
        }
      },
    });
    function conferenceMaterialsListFun(id, tabIndex) {
      $.ajax({
        type: "get",
        async: true, //异步执行
        url: base_url + "/meeting/detail/" + id,
        headers: {
          Accept: "application/json; charset=utf-8",
          Authorization: layui.sessionData("userToken").key,
        },
        contentType: "application/json",
        success: function (data) {
          if (data.code == 200) {
            if (data.data.hasOwnProperty("files")) {
              var files = data.data.files;
              table.render({
                elem: ".meetingProjectDocTable" + tabIndex,
                id: "#meetingProjectDocTable" + tabIndex,
                data: files || [],
                skin: "nob",
                cols: [
                  [
                    {
                      field: "fileName",
                      title: "文档名称",
                      align: "center",
                    },
                    {
                      field: "createTime",
                      title: "上传时间",
                      align: "center",
                    },
                    {
                      field: "userNumber",
                      title: "上传人",
                      align: "center",
                    },
                    {
                      title: "操作",
                      align: "center",
                      fixed: "right",
                      width: 200,
                      toolbar: "#meetingDocOprea",
                    },
                  ],
                ],
              });

              table.on(
                "tool(meetingProjectDocTable" + tabIndex + ")",
                function (obj) {
                  var data = obj.data;
                  if (obj.event === "meetingDocDown") {
                    window.location.href =
                      base_url + "/meeting/download/" + data.id;
                  } else if (obj.event === "meetingDocDelete") {
                    layer.confirm("确认删除吗?", function (index) {
                      $.ajax({
                        type: "get",
                        async: true, //异步执行
                        url: base_url + "/meeting/file/delete/" + data.id,
                        headers: {
                          Accept: "application/json; charset=utf-8",
                          Authorization: layui.sessionData("userToken").key,
                        },
                        contentType: "application/json",
                        success: function (data) {
                          if ((data.type = "success")) {
                            obj.del();
                            layer.close(index);
                            table.reload(
                              "meetingProjectDocTable" + tabIndex + ""
                            );
                            layer.msg(data.message, { icon: 6 });
                          } else {
                            layer.msg(data.message, { icon: 5 });
                          }
                        },
                      });
                    });
                  }
                }
              );
            }
            if (data.data.hasOwnProperty("voices")) {
              var voices = data.data.voices;
              voices.forEach((item, index) => {
                var htmlVido = `<div class="waveform" id="waveform_${tabIndex}_${index}" style="width: 100%; height: 100px"></div>
                <audio class="audio"
                id="audio_${tabIndex}_${index}"
                src="video.mp4"
                controls="" width="100%"
              ><a></a></audio><div class="meetingOpearBtn" data-id="${item.id}">
                <div class="meetingSummaryEdit"><i class="layui-icon layui-icon-edit"></i>保存</div>
              <div class="meetingSummaryDown"><i class="layui-icon layui-icon-download-circle"></i>下载</div>
              </div> <div class="turnText"> <textarea class="turnTextCon turnTextCon${index}">${item.text}</textarea></div>`;
                element.tabAdd("meetingVoicesTab" + tabIndex, {
                  title: "音频" + (index + 1), //用于演示
                  content: htmlVido,
                  id: index,
                });
              });
              element.on(
                "tab(meetingVoicesTab" + tabIndex + ")",
                function (data) {
                  wavesurferFun(data.index, tabIndex);
                }
              );
              element.tabChange("meetingVoicesTab" + tabIndex, 0);
            } else {
              $(".meetingVoicesTabList").html("");
            }
            $(".meetingSummaryEdit").on("click", function () {
              var id = $(this).parent().attr("data-id");
              $.ajax({
                url: base_url + "/meeting/update/meetingSummary",
                async: true,
                type: "post",
                data: {
                  id: id,
                  data: $(".turnTextCon").val(),
                },
                headers: {
                  Accept: "application/json; charset=utf-8",
                  Authorization: layui.sessionData("userToken").key,
                },
                success: function (data) {
                  if (data.code == "200") {
                    layer.msg(data.message, { icon: 1 });
                  }
                },
              });
            });
            // 会议纪要下载
            $(".meetingSummaryDown").on("click", function () {
              var id = $(this).parent().attr("data-id");
              window.location.href = base_url + "/meeting/download/" + id;
            });
          }
        },
      });
    }

    function wavesurferFun(index, tabIndex) {
      $(".meetingSummaryEdit").on("click", function () {
        var id = $(this).parent().attr("data-id");
        $.ajax({
          url: base_url + "/meeting/update/meetingSummary",
          async: true,
          type: "post",
          data: {
            id: id,
            data: document.getElementsByClassName(`turnTextCon${index}`)
              .innerHTML,
          },
          headers: {
            Accept: "application/json; charset=utf-8",
            Authorization: layui.sessionData("userToken").key,
          },
          success: function (data) {
            if (data.code == "200") {
              layer.msg(data.message, { icon: 1 });
            }
          },
        });
      });
      // 会议纪要下载
      $(".meetingSummaryDown").on("click", function () {
        var id = $(this).parent().attr("data-id");
        window.location.href = base_url + "/meeting/download/" + id;
      });
      if (
        document
          .getElementById(`waveform_${tabIndex}_${index}`)
          .getElementsByTagName("wave").length > 0
      ) {
        return;
      }
      wavesurfer && wavesurfer.destroy(); // 销毁重新渲染
      var audio = document.getElementById(`audio_${tabIndex}_${index}`);
      wavesurfer = WaveSurfer.create({
        container: `#waveform_${tabIndex}_${index}`, //#waveform_0_1  #waveform_0_2
        hideScrollbar: true, // 横坐标显示
        barWidth: true, // 波形展示为柱状
        height: 100,
        padding: 5,
        backgroundColor: "#EEF3EF",
        waveScale: 0.8,
        mediaType: "audio",
      });
      wavesurfer.load(audio.getAttribute("src"));
      var audios = document.getElementsByTagName("audio");
      // 暂停函数
      function pauseAll() {
        var self = this;
        [].forEach.call(audios, function (i) {
          // 将audios中其他的audio全部暂停
          i !== self && i.pause();
        });
      }
      // 给play事件绑定暂停函数
      [].forEach.call(audios, function (i) {
        i.addEventListener("play", pauseAll.bind(i));
      });

      audio.addEventListener("playing", function () {
        wavesurfer.play();
      });
      audio.addEventListener("pause", function () {
        wavesurfer.pause();
      });
      audio.addEventListener("seeked", function () {});
      audio.addEventListener("muted", function () {});
    }

    $(".backPreviousPage").on("click", function () {
      window.history.back(-1);
    });
    exports("projectManagementDetail", {});
  }
);
